package com.example.demo.information.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.account.entity.SecurityUser;
import com.example.demo.account.entity.SysUserRole;
import com.example.demo.account.service.UserRoleService;
import com.example.demo.common.utils.*;
import com.example.demo.information.entity.*;
import com.example.demo.information.entity.info.StudentInfo;
import com.example.demo.information.service.*;
import com.example.demo.param.entity.Param;
import com.example.demo.param.service.ParamService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Slf4j
@Controller
public class PhotoController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private PhotoService photoService;
    @Autowired
    private HistoryPhotoService historyPhotoService;
    @Autowired
    private ImgUtils imgUtils;
    @Autowired
    private BjxxService bjxxService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private ParamService paramService;

    @RequestMapping("/resetPhoto")
    public String resetPhoto(){
        return "mobile/photoTake";
    }

    /**
     * 选择照片或者上传照片后先保存原图
     * @param file
     * @return
     */
    @RequestMapping("/stuOriginalPhotoDr")
    @ResponseBody
    public String stuOriginalPhotoDr(MultipartFile file){
        return uploadStuPhotoDrAndChoice(file,2);
    }

    /**
     * 选择照片或者上传照片后直接生成证件照
     */
    @RequestMapping("/stuPhotoDr")
    @ResponseBody
    public String stuPhotoDr(MultipartFile file){
        return uploadStuPhotoDrAndChoice(file,1);
    }

    /**
     * 选择导入的方式
     * @param file
     * @param uploadDrType  1 表示上传原图并给予转化成证件照   2 表示上传原图不给予转化证件照
     * @return
     */
    private String uploadStuPhotoDrAndChoice(MultipartFile file,Integer uploadDrType){
        String message = "error";int code=1;//code 0 成功  1 失败
        Map<String,Object> map = new HashMap<>();
        map.put("data","");
        map.put("code",code);
        map.put("msg",message);
        String checkMsg = PhotoUtils.checkPhotoFile(file);
        if(!"true".equals(checkMsg)){
            map.put("msg",checkMsg);
            return JSON.toJSONString(map);
        }
        Date date = new Date();
        String xgsj = Constant.formatter.get().format(date);
        String localRoot = Constant.tempTempFolder+Constant.formatter2.get().format(date)+"/";
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        Student student = studentService.findBySfz(currentUserDetails.getUsername());
        String fileSaveName = student!=null?student.getSfz()+xgsj:xgsj;
        String objectName = student!=null&&student.getSchool()!=null
                ?String.valueOf(student.getSchool().getId())+"/":"null/";
        StudentInfo studentInfo = new StudentInfo(student);
        try{
            Map<String,String> paramMap = new HashMap<>();
            if(uploadDrType!=null&&uploadDrType==1){//uploadDrType==1 表示上传原图并给予转化成证件照
                paramMap = photoService
                        .stuOriginalPhotoToPassportAndSave(file,studentInfo,objectName,fileSaveName,date,localRoot);
            }else{//uploadDrType==2  表示上传原图不给予转化证件照
                paramMap = photoService
                        .stuOriginalPhotoAndSave(file,studentInfo,objectName,fileSaveName,date,localRoot);
            }
            String resultMsg = paramMap!=null&&paramMap.containsKey("msg")?paramMap.get("msg"):"error";
            if(!Constant.SUCCESS.equals(resultMsg)){
                return resultMsg;
            }
            String photoMsg = historyPhotoService.saveTempPhotoByStudent(
                    student
                    ,paramMap.get("spId")
                    ,paramMap.get("bkColor")
                    ,paramMap.get("ytPhotoObjectName")
                    ,paramMap.get("resultSaveObjectName")
                    ,paramMap.get("internetPath")
                    ,currentUserDetails.getName(),xgsj);
            if(!"success".equals(photoMsg)){
                map.put("msg","证件照保存失败.原因:"+photoMsg);
                return JSON.toJSONString(map);
            }
            map.put("code",0);
            map.put("msg","success");
            return JSON.toJSONString(map);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg","生成证件照失败.");
            return JSON.toJSONString(map);
        }
    }

    @RequestMapping("/admitTempPhoto")
    @ResponseBody
    public String admitTempPhoto(@RequestParam("address") Long tempPhotoId){

        Historyphoto tempPhoto = historyPhotoService.findById(tempPhotoId);
        if(tempPhoto==null){
            return "证件照不存在，请重新拍摄。";
        }
        String message = photoService.saveHistoryPhoto(tempPhoto);
        return message;
    }

    /**
     * 加载图片  (正式使用的)
     * @param photoId
     * @param request
     * @param response
     */
    private void loadPhoto(Long photoId,HttpServletRequest request, HttpServletResponse response){
        String addressStr = "";
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        addressStr = path + Constant.defaultPhotoPath;//默认图片
        addressStr = "C:/sl.png";
        if (photoId != null) {
            Photo photo= photoService.findById(photoId);
            addressStr = photo!=null?photo.getSavepath():addressStr;
        }
        System.out.println("加载的图片路径："+addressStr);
        try {
            imgUtils.queryPic(addressStr,request,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/getPhoto")
    @ResponseBody
    public void getPhoto(HttpServletRequest request, HttpServletResponse response) {
        loadPhoto(null,request,response);
    }

    @GetMapping("/getPhoto/{address}")
    public void getPhoto(@PathVariable("address") Long address
            ,HttpServletRequest request, HttpServletResponse response) {
        loadPhoto(address, request, response);
    }

    @RequestMapping("/getTempPhoto")
    @ResponseBody
    public void getTempPhoto(HttpServletRequest request, HttpServletResponse response) {
        loadTempPhoto(null,request,response);
    }

    @GetMapping("/getTempPhoto/{address}")
    public void getTempPhoto(@PathVariable("address") Long address
            ,HttpServletRequest request, HttpServletResponse response){
        loadTempPhoto(address,request,response);
    }

    /**
     * 加载图片  (历史拍摄记录)
     * @param photoId
     * @param request
     * @param response
     */
    private void loadTempPhoto(Long photoId, HttpServletRequest request, HttpServletResponse response) {
        String addressStr = "";
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        addressStr = path + Constant.defaultPhotoPath;//默认图片
        if (photoId != null) {
            Historyphoto historyPhoto = historyPhotoService.findById(photoId);
            addressStr = historyPhoto!=null?historyPhoto.getSavepath():addressStr;
        }
        System.out.println("加载的图片路径："+addressStr);
        try {
            imgUtils.queryPic(addressStr,request,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/toPhotoCheck")
    public String toPhotoCheck(ModelMap map){
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        SysUserRole role = currentUserDetails.getCurrSysUserRole();
        if("1".equals(currentUserDetails.getLgType())&&role.getRole_id()== Constant.STUDENT_ID){
            Student student = studentService.findBySfz(currentUserDetails.getUsername());
            Historyphoto historyphoto= historyPhotoService.findByXsxxIdAndXxxxIdAndBjxxId(student.getId()
                    ,student.getSchool().getId(),student.getBjxx().getId());
            String objectName = Constant.defaultPhotoObjectName;
            if(historyphoto!=null){
                objectName = historyphoto.getYtpath();
                map.addAttribute("addressId",historyphoto.getId());
            }
            PhotoOSSUtils oss = new PhotoOSSUtils();
            /*map.addAttribute("address",oss.urlLoadOneStuPhoto(objectName
                    ,Constant.defaultPhotoParamWidth,Constant.defaultPhotoParamHeight,Constant.defaultPhotoUrlTime));*/
            /*map.addAttribute("address",oss.urlLoadOneStuPhotoByInfo(objectName
                    ,Constant.defaultPhotoUrlTime));*/
            map.addAttribute("address",oss.urlLoadOneStuPhotoByInfoLimitMAX(objectName
                    ,Constant.defaultBrowerMaxPhotoParamWidth,Constant.defaultBrowerMaxPhotoParamHeight,Constant.defaultPhotoUrlTime));
            return "mobile/photoCheck";
        }else{
            return "index";
        }
    }

    @RequestMapping("/toPhotoMake")
    public String toPhotoMake(ModelMap map){
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        SysUserRole role = currentUserDetails.getCurrSysUserRole();
        if("1".equals(currentUserDetails.getLgType())&&role.getRole_id()== Constant.STUDENT_ID){
            Student student = studentService.findBySfz(currentUserDetails.getUsername());
            Historyphoto historyphoto= historyPhotoService.findByXsxxIdAndXxxxIdAndBjxxId(student.getId()
                    ,student.getSchool().getId(),student.getBjxx().getId());
            String objectName = Constant.defaultPhotoObjectName;
            if(historyphoto!=null){
                objectName = historyphoto.getSavepath();
                map.addAttribute("addressId",historyphoto.getId());
            }
            PhotoOSSUtils oss = new PhotoOSSUtils();
            /*map.addAttribute("address",oss.urlLoadOneStuPhoto(objectName
                    ,Constant.defaultPhotoParamWidth,Constant.defaultPhotoParamHeight,Constant.defaultPhotoUrlTime));*/
            /*map.addAttribute("address",oss.urlLoadOneStuPhotoByInfo(objectName
                    ,Constant.defaultPhotoUrlTime));*/
            map.addAttribute("address",oss.urlLoadOneStuPhotoByInfoLimitMAX(objectName
                    ,Constant.defaultBrowerMaxPhotoParamWidth,Constant.defaultBrowerMaxPhotoParamHeight,Constant.defaultPhotoUrlTime));
            return "mobile/photoMake";
        }else{
            return "index";
        }
    }

    @RequestMapping("/transformOriginal")
    @ResponseBody
    public String transformOriginal(@RequestParam("address") Long tempPhotoId){
        /*try{
            //Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        Historyphoto tempPhoto = historyPhotoService.findById(tempPhotoId);
        if(tempPhoto==null){
            return "原照不存在，请重新拍摄。";
        }
        //转化原图->证件照
        Date date = new Date();
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        String xgsj = Constant.formatter.get().format(date);
        String localRoot = Constant.tempTempFolder+Constant.formatter2.get().format(date)+"/";
        Student student = studentService.findById(tempPhoto.getXsxxId());
        School school = schoolService.findById(tempPhoto.getXxxxId());
        Bjxx bjxx = bjxxService.findById(tempPhoto.getBjxxId());
        StudentInfo studentInfo = new StudentInfo(student,bjxx,school);
        Map<String,String> paramMap = photoService.tranformOriginal(studentInfo,tempPhoto.getYtpath(),date,localRoot);
        String message = !paramMap.containsKey("msg")?"error":paramMap.get("msg");
        if(!message.equals("success")){
            return message;
        }
        String resultMsg = paramMap!=null&&paramMap.containsKey("msg")?paramMap.get("msg"):"error";
        if(!Constant.SUCCESS.equals(resultMsg)){
            return resultMsg;
        }
        String photoMsg = historyPhotoService.updateTempPhotoByResultInfo(
                tempPhoto
                ,paramMap.get("spId")
                ,paramMap.get("bkColor")
                ,paramMap.get("resultSaveObjectName")
                ,paramMap.get("internetPath")
                ,currentUserDetails.getName(),xgsj);
        if(!Constant.SUCCESS.equals(photoMsg)){
            return "证件照保存失败.原因:"+photoMsg;
        }else{
            return Constant.SUCCESS;
        }
    }

    @RequestMapping("/toPhoto")
    public String toPhoto(ModelMap map){
        List<Student> stuList = studentService.findAll();
        stuList = studentService.findByRoleForStudentList(stuList);
        List<StudentInfo> stuInfoList = getStuInfoFromStu(stuList,Constant.defaultPhotoParamRatio,Constant.rangePhotoSet);
        int count = stuInfoList.size();
        stuInfoList = studentService.getCurrPageByStuInfoList(stuInfoList,Constant.defaultParamCurr, Constant.defaultParamLimit);
        PhotoOSSUtils oss = new PhotoOSSUtils();
        stuInfoList = oss.setPhotoUrl(stuInfoList);
        map.addAttribute("stuInfoList",stuInfoList);
        map.addAttribute("count",count);
        return "information/photo/photoList";
    }

    /**
     * 刷新页面的照片list
     * @param model
     * @param searchVal 搜索学生内容(姓名\身份证\学籍辅号)
     * @param id (xxId\bjId\xsId)
     * @param type (school\bjxx\student)
     * @param range 搜索照片范围(全部\已设置\未设置)
     * @return
     */
    @RequestMapping("/refrashPhoto")
    public String refrashPhoto(Model model, String searchVal,Long id,String type,@RequestParam("tab") String range
            ,Integer curr,Integer limit){
        List<Student> stuList = studentService.findByTypeAndSearch(searchVal,id,type);
        stuList = studentService.findByRoleForStudentList(stuList);
        List<StudentInfo> stuInfoList = getStuInfoFromStu(stuList,Constant.defaultPhotoParamRatio,range);
        int count = stuInfoList.size();
        stuInfoList = studentService.getCurrPageByStuInfoList(stuInfoList,curr,limit);
        PhotoOSSUtils oss = new PhotoOSSUtils();
        stuInfoList = oss.setPhotoUrl(stuInfoList);
        model.addAttribute("stuInfoList",stuInfoList);
        model.addAttribute("count",count);
        return "information/photo/photoList::stu_PhotoPre";
    }



    /**
     * 获得学生对象(含照片信息)
     * @param studentList 需要查找的学生list
     * @param ratio 照片的大小比例
     * @param range 照片范围(全部\未设置\已设置)(选项卡)
     * @return
     */
    private List<StudentInfo> getStuInfoFromStu(List<Student> studentList,float ratio,String range){
        int width = Integer.valueOf(Constant.defaultPhotoParamWidth);
        int height = Integer.valueOf(Constant.defaultPhotoParamHeight);
        int urlTime = Constant.defaultPhotoUrlTime;
        int newWidth = (int)((float)width * ratio);
        int newHeight = (int)((float)height * ratio);
        String widthStr = String.valueOf(newWidth);
        String heightStr = String.valueOf(newHeight);
        List<StudentInfo> list = new ArrayList<>();
        for(Student  s :studentList){
            StudentInfo stuInfo = new StudentInfo(s);
            Photo photo = photoService.findByXsxxIdAndXxxxIdAndBjxxId(s.getId(), s.getSchool().getId(), s.getBjxx().getId());
            if(photo!=null){
                stuInfo.setAddress(photo.getId());
                stuInfo.setAddressStr(photo.getSavepath());
                stuInfo.setYtAddressStr(photo.getYtpath());
            }
            stuInfo.setWidth(widthStr);
            stuInfo.setHeight(heightStr);
            stuInfo.setUrlTime(urlTime);
            if(StringUtils.isBlank(range)){//全部
                list.add(stuInfo);
            }else{
                if(Constant.rangePhotoSet.equals(range)&&photo!=null){//已设置
                    list.add(stuInfo);
                }else if(Constant.rangePhotoNoSet.equals(range)&&photo==null){//未设置
                    list.add(stuInfo);
                }
            }
        }
        return list;
    }
    /**
     * 导出学生证件照
     * @param xxxxId
     * @param bjxxId
     * @param xsIds
     * @param response
     */
    @RequestMapping("/expStuPhoto")
    public void expStuPhoto(Long xxxxId,Long bjxxId,String xsIds,HttpServletResponse response){
        List<Student> stuList = studentService.getStuByXxxxIdBjxxIdXsIds(xxxxId,bjxxId,xsIds);
        if(stuList==null||stuList.isEmpty()){return;}
        try {
            photoService.downLoadStuPhoto(stuList,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出学生个人照片
     * @param ids  xsId@@bjxxId
     * @param type 导出照片的种类 type
     */
    @RequestMapping("expOwnStuPhoto")
    public void expOwnStuPhoto(String ids,String type,HttpServletResponse response){
        if(StringUtils.isBlank(ids)){
            SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
            if(Constant.STUDENT_ID.equals(currentUserDetails.getCurrSysUserRole().getRole_id())){
                Student student = studentService.findBySfz(currentUserDetails.getSfz());
                if(student==null){return;}
                ids = student.getId() + "@@" + (student.getBjxx()!=null?String.valueOf(student.getBjxx().getId()):"");
            }
        }
        if(StringUtils.isBlank(ids)||ids.lastIndexOf("@@")==-1){
            return;
        }
        Photo photo;String fileName="";
        try{
            type = StringUtils.isBlank(type)?Constant.typePhotoAll:type;
            String[] split = ids.split("@@");
            Long xsxxId = Long.valueOf(split[0]);
            Student stu = studentService.findById(xsxxId);
            Long bjxxId = Long.valueOf(split[1]);
            Bjxx bjxx = bjxxService.findById(bjxxId);
            StudentInfo studentInfo = new StudentInfo(stu,bjxx,bjxx.getSchool());
            fileName = paramService.getPhotoFileNameByStudentInfo(studentInfo);
            photo = photoService.findByXsxxIdAndXxxxIdAndBjxxId(xsxxId, bjxx.getSchool().getId(), bjxxId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("找不到对应的证件照,stuId,bjId:"+ids);
            return;
        }
        try{
            photoService.downLoadStuPhotoOwn(fileName,photo,type,response);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("证件照下载失败,stuId,bjId:"+ids+",photoId:"+(photo!=null?photo.getId():"null"));
            return;
        }
    }

    @RequestMapping("/toStuPhotoAdd")
    public String toStuPhotoAdd(){
        return "information/photo/photoExp";
    }

    @RequestMapping("/reupOwnStuPhoto")
    @ResponseBody
    public String reupOwnStuPhoto(@RequestParam("ids")String ids,String type,MultipartFile file){
        System.out.println(ids+type);
        System.out.println(file.getOriginalFilename());
        String msg = "error";
        Map<String,Object> map = new HashMap<>();
        map.put("data","");
        map.put("code",1);
        if(StringUtils.isBlank(ids)||ids.lastIndexOf("@@")==-1) {
            msg = "参数异常，请重新尝试，";
            map.put("msg", msg);
            return JSON.toJSONString(map);
        }
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        String checkMsg = PhotoUtils.checkPhotoFile(file);
        if(!"true".equals(checkMsg)){
            map.put("msg",checkMsg);
            return JSON.toJSONString(map);
        }
        try {
            String[] split = ids.split("@@");
            Long xsId = Long.parseLong(split[0]);
            Long bjId = Long.parseLong(split[1]);
            type = StringUtils.isBlank(type)?Constant.typePhotoOri:type;
            Student student = studentService.findById(xsId);
            Bjxx bjxx = bjxxService.findById(bjId);
            School school = bjxx.getSchool();
            StudentInfo studentInfo = new StudentInfo(student,bjxx,school);
            Date date = new Date();
            String xgsj = Constant.formatter.get().format(date);
            String localRoot = Constant.tempTempFolder+Constant.formatter2.get().format(date)+"/";
            String fileSaveName = student!=null?student.getSfz()+xgsj:xgsj;
            String objectName = school!=null?String.valueOf(student.getSchool().getId())+"/":"null/";
            Historyphoto historyphoto = null;
            Map<String,String> paramMap = new HashMap<>();
            if(Constant.typePhotoPas.equals(type)){//直接存证件照
                paramMap = photoService
                        .stuPassportAndSave(file,studentInfo,objectName,fileSaveName,date,localRoot,"999","999");
            }else{//Constant.typePhotoOri原图  要调用接口转换下
                paramMap = photoService
                        .stuOriginalPhotoToPassportAndSave(file,studentInfo,objectName,fileSaveName,date,localRoot);
            }
            String resultMsg = paramMap!=null&&paramMap.containsKey("msg")?paramMap.get("msg"):"error";
            if(!Constant.SUCCESS.equals(resultMsg)){
                map.put("msg",resultMsg);
                return JSON.toJSONString(map);
            }
            String photoMsg = historyPhotoService.saveTempPhotoByStudentInfo(
                    studentInfo
                    ,paramMap.get("spId")
                    ,paramMap.get("bkColor")
                    ,paramMap.get("ytPhotoObjectName")
                    ,paramMap.get("resultSaveObjectName")
                    ,paramMap.get("internetPath")
                    ,currentUserDetails.getName(),xgsj);
            msg = photoMsg;
            historyphoto = historyPhotoService.findByXsxxIdAndXxxxIdAndBjxxId(studentInfo.getXsId()
                    ,studentInfo.getXxxxId(),studentInfo.getBjxxId());
            msg = photoService.saveHistoryPhoto(historyphoto);
        } catch (Exception e) {
            e.printStackTrace();
            msg = "保存失败，联系管理员。";
        }
        map.put("msg",msg);
        return JSON.toJSONString(map);
    }

}
